<template>
  <div class="admin-container">
    <div id="adminMapView"></div>

    <!-- 状态指示器 -->
    <div class="status-indicator" v-if="isAddingMode">
      <div class="pulse-dot"></div>
      <span>请在地图上选择景点位置</span>
      <el-button size="small" @click="cancelAddingMode" class="cancel-btn">取消</el-button>
    </div>

    <!-- 功能按钮 -->
    <div class="feature-panel-button" @click="showFeaturePanel = true">
      <el-icon><Setting /></el-icon>
    </div>

    <!-- 功能面板 -->
    <el-drawer
      v-model="showFeaturePanel"
      title="景点管理"
      direction="rtl"
      size="300px"
      :with-header="false"
      class="custom-drawer"
    >
      <div class="drawer-header">
        <h2>景点管理</h2>
      </div>
      <div class="feature-actions">
        <el-button type="primary" @click="startAddingMode" :icon="Plus">创建景点</el-button>
        <el-button
          type="warning"
          @click="openUpdateDrawer"
          :disabled="!selectedFeatureId"
          :icon="Edit"
          >更新景点</el-button
        >
        <el-button
          type="danger"
          @click="deleteFeature"
          :disabled="!selectedFeatureId"
          :icon="Delete"
          >删除景点</el-button
        >
      </div>

      <div class="feature-instructions" v-if="!selectedFeatureId && !isAddingMode">
        <el-alert type="info" :closable="false" show-icon>
          <template #title>请在地图上选择景点以便更新或删除</template>
        </el-alert>
      </div>

      <div class="selected-feature" v-if="selectedFeatureId">
        <div class="selected-title">当前选中景点</div>
        <div class="selected-name">{{ selectedFeatureName }}</div>
        <div class="selected-type">
          <el-tag type="info">
            {{ getTypeLabel(selectedFeatureType) }}
          </el-tag>
        </div>
      </div>
    </el-drawer>

    <!-- 创建/更新景点抽屉 -->
    <el-drawer
      v-model="showEditorDrawer"
      :title="isEditing ? '更新景点' : '创建景点'"
      direction="rtl"
      size="400px"
      :with-header="false"
      class="custom-drawer"
    >
      <div class="drawer-header">
        <h2>{{ isEditing ? '更新景点' : '创建景点' }}</h2>
      </div>
      <el-form :model="formData" label-width="100px" class="feature-form">
        <el-form-item label="景点名称">
          <el-input v-model="formData.name" placeholder="请输入景点名称"></el-input>
        </el-form-item>
        <el-form-item label="景点类型">
          <el-select
            v-model="formData.type"
            placeholder="请选择景点类型"
            clearable
            filterable
            allow-create
          >
            <el-option
              v-for="type in attractionTypes"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="formData.description"
            type="textarea"
            rows="4"
            placeholder="请输入景点描述"
          ></el-input>
        </el-form-item>
        <el-form-item label="景点照片">
          <el-upload
            class="avatar-uploader"
            action="#"
            :auto-upload="false"
            :show-file-list="false"
            :on-change="handleImageChange"
          >
            <div class="upload-area">
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <div v-else class="avatar-uploader-icon">
                <el-icon><Plus /></el-icon>
                <span>点击上传图片</span>
              </div>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item class="form-actions">
          <el-button type="primary" @click="saveFeature" :icon="Check">保存</el-button>
          <el-button @click="showEditorDrawer = false" :icon="Close">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Plus, Setting, Edit, Delete, Check, Close } from '@element-plus/icons-vue'
import Map from '@arcgis/core/Map'
import MapView from '@arcgis/core/views/MapView'
import FeatureLayer from '@arcgis/core/layers/FeatureLayer'
import Graphic from '@arcgis/core/Graphic'
import Point from '@arcgis/core/geometry/Point'
import gaodeLayer from '@/utils/GaoDeBaseLayer'
import { ElMessage, ElMessageBox } from 'element-plus'
import SimpleMarkerSymbol from '@arcgis/core/symbols/SimpleMarkerSymbol'

// 地图视图和图层
let view = new MapView()
let attractionsLayer = new FeatureLayer()

// UI 控制状态
const showFeaturePanel = ref(false)
const showEditorDrawer = ref(false)
const isEditing = ref(false)
const selectedFeatureId = ref<number | null>(null)
const selectedFeatureName = ref('')
const isAddingMode = ref(false)
let newPointLocation: Point | null = new Point()
const selectedFeatureType = ref('')
const clickHandler: IHandle | null = null

// 表单数据
const formData = ref({
  name: '',
  description: '',
  imageBase64: '',
  type: '',
})

// 预设景点类型选项
const attractionTypes = ref([
  { value: 'natural', label: '自然风光' },
  { value: 'historical', label: '历史文化' },
  { value: 'entertainment', label: '休闲娱乐' },
])

// 类型标签显示方法
const getTypeLabel = (value: string) => {
  const type = attractionTypes.value.find(t => t.value === value)
  return type ? type.label : value
}

// 图片预览URL
const imageUrl = ref('')

// 初始化地图
const initMap = async () => {
  const map = new Map({
    basemap: {
      baseLayers: [gaodeLayer],
    },
  })

  view = new MapView({
    container: 'adminMapView',
    map: map,
    center: [117.025711, 36.6752],
    zoom: 15,
    popup: {
      dockEnabled: true,
      dockOptions: {
        buttonEnabled: false,
        breakpoint: false,
      },
    },
  })

  // 定义景点图层
  attractionsLayer = new FeatureLayer({
    url: 'https://services5.arcgis.com/HfcuJ9RUSlysODB4/arcgis/rest/services/ScenicPoint/FeatureServer/0',
    outFields: ['*'],
    popupEnabled: false,
    renderer: {
      type: "unique-value",
      field: "SpotType",
      defaultSymbol: {
        type: "simple-marker",
        size: 14,
        color: [156, 156, 156, 0.8], // 默认灰色
        outline: {
          color: [255, 255, 255],
          width: 2
        }
      },
      uniqueValueInfos: [
        {
          value: "historical",
          symbol: {
            type: "simple-marker",
            style: "square",
            size: 14,
            color: [230, 97, 97, 0.8], // 红色系
            outline: {
              color: [255, 255, 255],
              width: 2
            }
          }
        },
        {
          value: "natural",
          symbol: {
            type: "simple-marker",
            style: "circle",
            size: 14,
            color: [75, 166, 127, 0.8], // 绿色系
            outline: {
              color: [255, 255, 255],
              width: 2
            }
          }
        },
        {
          value: "entertainment",
          symbol: {
            type: "simple-marker",
            style: "diamond",
            size: 14,
            color: [95, 150, 224, 0.8], // 蓝色系
            outline: {
              color: [255, 255, 255],
              width: 2
            }
          }
        }
      ]
    },
    // 添加标注
    labelingInfo: [{
      symbol: {
        type: "text",
        color: "#333333",
        haloColor: "#ffffff",
        haloSize: 2,
        font: {
          size: 12,
          weight: "normal"
        }
      },
      labelPlacement: "above-center",
      labelExpressionInfo: {
        expression: "$feature.SpotName"
      },
      minScale: 5000, // 当地图缩放到多少比例尺以内才显示标签
      maxScale: 0
    }]
  })
  map.add(attractionsLayer)

  // 添加点击事件监听器以选择要素
  view.on('click', async (event) => {
    if (isAddingMode.value) {
      handleAddingModeClick(event)
      return
    }

    const hitResults = (await view?.hitTest(event))?.results as __esri.MapViewGraphicHit[]
    const feature = hitResults.find((result) => result.layer?.id === attractionsLayer?.id)?.graphic

    if (feature) {
      selectedFeatureId.value = feature.attributes.OBJECTID
      selectedFeatureName.value = feature.attributes.SpotName || `景点 #${selectedFeatureId.value}`
      selectedFeatureType.value = feature.attributes.SpotType

      // 添加高亮效果
      view?.graphics.removeAll()
      const highlightSymbol = new SimpleMarkerSymbol({
        color: [255, 255, 255, 0.8],
        size: 16,
        outline: {
          color: [0, 122, 194],
          width: 3,
        },
      })

      const highlightGraphic = new Graphic({
        geometry: feature.geometry,
        symbol: highlightSymbol,
      })

      view?.graphics.add(highlightGraphic)
    } else {
      selectedFeatureId.value = null
      selectedFeatureName.value = ''
      view?.graphics.removeAll()
    }
  })
}

// 启动添加景点模式
const startAddingMode = () => {
  isAddingMode.value = true
  showFeaturePanel.value = false
  view?.graphics.removeAll()

  // 更改鼠标样式
  if (view?.container) {
    ;(view.container as HTMLElement).style.cursor = 'crosshair'
  }
}

// 取消添加景点模式
const cancelAddingMode = () => {
  isAddingMode.value = false
  newPointLocation = null

  // 还原鼠标样式
  if (view?.container) {
    ;(view.container as HTMLElement).style.cursor = 'default'
  }

  view?.graphics.removeAll()
}

// 处理添加模式下的点击
const handleAddingModeClick = (event: __esri.ViewClickEvent) => {
  // 创建一个点
  newPointLocation = new Point({
    longitude: event.mapPoint.longitude,
    latitude: event.mapPoint.latitude,
    spatialReference: view?.spatialReference,
  })

  // 显示临时标记
  view?.graphics.removeAll()
  const tempSymbol = new SimpleMarkerSymbol({
    color: [0, 122, 194, 0.5],
    size: 14,
    outline: {
      color: [255, 255, 255],
      width: 2,
    },
  })

  const tempGraphic = new Graphic({
    geometry: newPointLocation,
    symbol: tempSymbol,
  })

  view?.graphics.add(tempGraphic)

  // 打开创建表单
  isAddingMode.value = false
  isEditing.value = false
  resetForm()
  showEditorDrawer.value = true

  // 还原鼠标样式
  if (view?.container) {
    ;(view.container as HTMLElement).style.cursor = 'default'
  }
}

// 打开创建抽屉
const openCreateDrawer = () => {
  isEditing.value = false
  resetForm()
  showEditorDrawer.value = true
}

// 打开更新抽屉
const openUpdateDrawer = async () => {
  if (!selectedFeatureId.value) {
    ElMessage.warning('请先选择一个景点')
    return
  }

  isEditing.value = true

  try {
    // 查询选中的要素
    const query = attractionsLayer?.createQuery()
    query.where = `OBJECTID = ${selectedFeatureId.value}`
    query.outFields = ['*']

    const result = await attractionsLayer?.queryFeatures(query)
    const feature = result?.features[0]

    if (feature) {
      formData.value.name = feature.attributes.SpotName || ''
      formData.value.description = feature.attributes.SpotIntroduction || ''
      formData.value.type = feature.attributes.SpotType || '' // 加载类型

      // 加载图片
      if (feature.attributes.IntroduceImageBase64) {
        formData.value.imageBase64 = feature.attributes.IntroduceImageBase64
        imageUrl.value = feature.attributes.IntroduceImageBase64
      } else {
        imageUrl.value = ''
      }

      showEditorDrawer.value = true
    }
  } catch (error) {
    console.error('获取景点数据失败', error)
    ElMessage.error('获取景点数据失败')
  }
}

// 删除要素
const deleteFeature = async () => {
  if (!selectedFeatureId.value) {
    ElMessage.warning('请先选择一个景点')
    return
  }

  try {
    await ElMessageBox.confirm(`确定要删除景点 "${selectedFeatureName.value}" 吗？`, '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    const attributes = {
      OBJECTID: selectedFeatureId.value,
    }
    // 创建一个新的图形对象
    const deleteFeature = new Graphic({
      attributes: attributes,
    })

    attractionsLayer?.applyEdits({
      deleteFeatures: [deleteFeature],
    })

    ElMessage.success('景点已删除')
    selectedFeatureId.value = null
    selectedFeatureName.value = ''
    view?.graphics.removeAll()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除景点失败', error)
      ElMessage.error('删除景点失败')
    }
  }
}

// 图片上传处理
const handleImageChange = (file: { raw: Blob }) => {
  const reader = new FileReader()
  reader.readAsDataURL(file.raw)
  reader.onload = () => {
    imageUrl.value = reader.result as string
    formData.value.imageBase64 = reader.result as string
  }
}

// 保存要素
const saveFeature = async () => {
  if (!formData.value.name) {
    ElMessage.warning('请输入景点名称')
    return
  }

  try {
    const attributes = {
      SpotName: formData.value.name,
      SpotIntroduction: formData.value.description,
      SpotType: formData.value.type, // 映射到要素字段
      IntroduceImageBase64: formData.value.imageBase64,
    }

    if (isEditing.value && selectedFeatureId.value) {
      // 更新现有要素
      const updateFeature = new Graphic({
        attributes: {
          OBJECTID: selectedFeatureId.value,
          ...attributes,
        },
      })

      attractionsLayer?.applyEdits({
        updateFeatures: [updateFeature],
      })

      ElMessage.success('景点已更新')
    } else {
      // 创建新要素
      if (!newPointLocation) {
        ElMessage.warning('无法获取景点位置')
        return
      }

      const graphic = new Graphic({
        geometry: newPointLocation,
        attributes: attributes,
      })

      attractionsLayer?.applyEdits({
        addFeatures: [graphic],
      })

      ElMessage.success('景点已创建')
      newPointLocation = null
    }

    // 关闭抽屉并重置表单
    showEditorDrawer.value = false
    resetForm()
    view?.graphics.removeAll()
  } catch (error) {
    console.error('保存景点失败', error)
    ElMessage.error('保存景点失败')
  }
}

// 重置表单
const resetForm = () => {
  formData.value = {
    name: '',
    description: '',
    imageBase64: '',
    type: '',
  }
  imageUrl.value = ''
}

onMounted(() => {
  initMap()
})
</script>

<style scoped>
.admin-container {
  position: relative;
  height: 100vh;
  font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
}

#adminMapView {
  width: 100%;
  height: 100%;
}

/* 功能按钮 */
.feature-panel-button {
  position: absolute;
  right: 20px;
  top: 20px;
  width: 44px;
  height: 44px;
  background: white;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  cursor: pointer;
  z-index: 10;
  transition: all 0.3s ease;
}

.feature-panel-button:hover {
  background: #f0f7ff;
  transform: translateY(-2px);
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.2);
}

/* 状态指示器 */
.status-indicator {
  position: absolute;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 10px 20px;
  border-radius: 30px;
  display: flex;
  align-items: center;
  gap: 10px;
  z-index: 100;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
}

.pulse-dot {
  width: 12px;
  height: 12px;
  background-color: #ff4d4f;
  border-radius: 50%;
  animation: pulse 1.5s infinite;
}

.cancel-btn {
  margin-left: 10px;
  height: 28px;
  padding: 0 10px;
}

@keyframes pulse {
  0% {
    transform: scale(0.8);
    opacity: 0.7;
  }
  50% {
    transform: scale(1.2);
    opacity: 1;
  }
  100% {
    transform: scale(0.8);
    opacity: 0.7;
  }
}

/* 抽屉样式 */
.custom-drawer :deep(.el-drawer__body) {
  padding: 0;
  overflow-y: auto;
}

.drawer-header {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
  background: #f9fafc;
}

.drawer-header h2 {
  margin: 0;
  font-size: 18px;
  color: #303133;
  font-weight: 600;
}

.feature-actions {
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 12px;
}
.el-button + .el-button {
  margin-left: 0px;
}

.feature-instructions {
  padding: 0 20px;
  margin-bottom: 20px;
}

.selected-feature {
  margin: 20px;
  padding: 15px;
  background: #f0f9eb;
  border-left: 4px solid #67c23a;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.selected-title {
  font-size: 14px;
  color: #67c23a;
  font-weight: 600;
  margin-bottom: 8px;
}

.selected-name {
  font-size: 16px;
  font-weight: 500;
}

/* 表单样式 */
.feature-form {
  padding: 20px;
}

.form-actions {
  margin-top: 30px;
}

.avatar-uploader {
  width: 100%;
}

.upload-area {
  display: flex;
  justify-content: center;
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  width: 100%;
  overflow: hidden;
}

.upload-area:hover {
  border-color: #409eff;
  background-color: #f5f7fa;
}

.avatar-uploader-icon {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 178px;
  color: #8c939d;
}

.avatar-uploader-icon i {
  font-size: 28px;
  margin-bottom: 8px;
}

.avatar {
  width: 100%;
  height: 178px;
  object-fit: cover;
  display: block;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .feature-panel-button {
    right: 10px;
    top: 10px;
  }

  .status-indicator {
    font-size: 12px;
    padding: 8px 16px;
  }
}

.selected-type {
  margin-top: 8px;
}

.el-tag {
  margin-right: 4px;
}

/* 扩展表单布局 */
.feature-form {
  .el-select {
    width: 100%;
  }
}
</style>
